package vip.xiaonuo.modular.encryptAndDecrypt;

import cn.hutool.extra.spring.SpringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import vip.xiaonuo.core.util.AesUtil;
import vip.xiaonuo.core.util.RsaUtil;
import vip.xiaonuo.sys.core.cache.PublicKeyCache;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 解密参数
 *
 * @author zhangbixi
 * @date
 */
public class DecryptHttpInputMessage implements HttpInputMessage {

    private PublicKeyCache publicKeyCache = SpringUtil.getBean(PublicKeyCache.class);

    private Logger log = LoggerFactory.getLogger(this.getClass());
    private HttpHeaders headers;
    private InputStream body;

    public DecryptHttpInputMessage(HttpInputMessage inputMessage, String privateKey, boolean showLog) throws Exception {
        if (StringUtils.isEmpty(privateKey)) {
            throw new IllegalArgumentException("privateKey is null");
        } else {
            this.headers = inputMessage.getHeaders();
            String content = (String) (new BufferedReader(new InputStreamReader(inputMessage.getBody()))).lines().collect(Collectors.joining(System.lineSeparator()));

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String decryptBody;
            if (!StringUtils.isEmpty(content)) {
                String[] contents = content.split(",");
                Map<String,String> map = new HashMap<>();
                for (int i = 0; i < 3; i++
                ) {
                    String[] param = contents[i].split(":");
                    map.put(param[0].substring(param[0].indexOf('"',0)+1, param[0].lastIndexOf('"')), param[1].substring(param[1].indexOf('"',0)+1, param[1].lastIndexOf('"')));
                }
                //获得前端用RSA公钥加密后的aesKey
                String aesKey = map.get("aesKey");
                //用RSA私钥解密aesKey
                byte[] plaintext = RsaUtil.decryptByPrivateKey(Base64.decodeBase64(aesKey), RsaUtil.getPrivateKey());
                aesKey = new String(plaintext);
                //获得aesKey前端用AES加密后的data
                String data = map.get("data");
                //AES解密得到明文data数据
                String decrypt = AesUtil.decrypt(data, aesKey);
                decryptBody = decrypt;
                //将publicKey存到redis缓存中
                System.out.println("存入的publicKey："+map.get("publicKey"));
                publicKeyCache.put("ENCRYPT",map.get("publicKey"));
                this.body = new ByteArrayInputStream(decryptBody.getBytes());
            }
        }
    }

    @Override
    public InputStream getBody() {
        return this.body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return this.headers;
    }
}
